package com.mars.framework.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.mars.common.base.UserContextInfo;
import com.mars.common.constant.Constant;
import com.mars.common.result.R;
import com.mars.common.enums.HttpCodeEnum;
import com.mars.common.util.JsonUtils;
import com.mars.common.util.TokenUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mars.framework.context.ContextUserInfoThreadHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * 权限拦截器
 *
 * @author 源码字节-程序员Mars
 */
public class AuthorityInterceptor implements HandlerInterceptor {

    private final TokenUtils tokenUtils;

    public AuthorityInterceptor(TokenUtils tokenUtils) {
        this.tokenUtils = tokenUtils;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getRequestURI();
        if (StringUtils.isNotEmpty(path)) {
            if (path.endsWith(Constant.HTML)) {
                return true;
            }
            UserContextInfo userInfo = tokenUtils.getUserInfo(request);
            if (Objects.isNull(userInfo)) {
                this.buildResponse(response);
                return false;
            }
            ContextUserInfoThreadHolder.set(userInfo);
        }
        return true;
    }

    private void buildResponse(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        pw.write(JsonUtils.toJsonString(R.error(HttpCodeEnum.TOKEN_INVALID.getCode(), HttpCodeEnum.TOKEN_INVALID.getMessage())));
        pw.flush();
        pw.close();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
        ContextUserInfoThreadHolder.remove();
    }
}
